<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--树结构-->
      <el-col :span="isHide ? 1 : 6" :xs="24" class="relative">
        <div class="app-container-tree-border">
          <project-tree-select-inner class="cd-mb8" :projectId="projectId" @changeProject="changeProject" />
          <el-input class="cd-mb8" v-model="filterText" placeholder="请输入" clearable size="small"
            prefix-icon="el-icon-search" />
          <el-tree class="input-tree" :data="treeList" :props="defaultProps" :filter-node-method="filterNode" ref="tree"
            node-key="id" highlight-current @node-click="handleNodeClick">
            <div slot-scope="{ node, data }" class="custom-tree-node" :title="node.label" v-text="node.label"></div>
          </el-tree>
          <div class="tree-hide-button iconfont" :class="isHide ? 'icon-xiangyou' : 'icon-xiangzuo'"
            @click="() => { isHide = !isHide }">
          </div>
        </div>
      </el-col>
      <el-col :span="isHide ? 23 : 18" :xs="24">
        <div class="app-container-table-border">
          <el-row v-if="treeInfo && treeInfo.type == 'supplier'" :gutter="10"
            class="mb8 cd-pr8 top-right-btn small-line-height">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                v-hasPermi="['ma:materialProgress:add']">新增</el-button>
            </el-col>
          </el-row>
          <el-table border stripe v-loading="loading" :data="materialProgressList"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="供货日期" align="center" prop="supplyDate" width="140" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.supplyDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="交接验收单据号" align="center" prop="acceptanceCode" min-width="120"
              show-overflow-tooltip />
            <el-table-column label="供货地点" align="center" prop="address" min-width="120" show-overflow-tooltip />
            <el-table-column label="施工单位对接人" align="center" prop="contactPerson" min-width="120"
              show-overflow-tooltip />
            <el-table-column label="电话" align="center" prop="phone" min-width="120" show-overflow-tooltip />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-view"
                  @click="handleUpdate(scope.row, 1)">查看</el-button>
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['ma:materialProgress:edit']">编辑</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['ma:materialProgress:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
      </el-col>
    </el-row>
    <!-- 添加或修改材料签收对话框 -->
    <jy-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="105px">
        <div v-if="!isReadonly">
          <el-row>
            <el-col :span="8">
              <el-form-item label="供货日期" prop="supplyDate">
                <el-date-picker clearable v-model="form.supplyDate" type="date" value-format="yyyy-MM-dd"
                  placeholder="请选择供货日期" style="width: 100%;" @change="getMaterialList">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="交接单据号" prop="acceptanceCode">
                <el-input v-model="form.acceptanceCode" placeholder="请输入交接验收单据号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="供货地点" prop="address">
                <el-input v-model="form.address" placeholder="请输入供货地点" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="施工单位对接人" prop="contactPerson">
                <el-input v-model="form.contactPerson" placeholder="请输入施工单位对接人" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="电话" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入电话" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="附件" prop="fileId">
            <fileUpload v-model="form.fileId" :oldList="form.fileIdOld" :fileType="['doc', 'docx', 'xlsx', 'xls'
              , 'pdf', 'png', 'jpg', 'jpeg']" :disabled="isReadonly" />
          </el-form-item>
        </div>
        <div v-else class="cd-mb16">
          <el-descriptions border title="" :column="3" size="medium" labelClassName="descriptions-label"
            contentClassName="descriptions-content">
            <el-descriptions-item label="供货日期：" span="1">
              {{ parseTime(form.supplyDate, '{y}-{m}-{d}') }}
            </el-descriptions-item>
            <el-descriptions-item label="交接单据号：" span="1">
              {{ form.acceptanceCode }}
            </el-descriptions-item>
            <el-descriptions-item label="供货地点：" span="1">
              {{ form.address }}
            </el-descriptions-item>
            <el-descriptions-item label="施工单位对接人：" span="1">
              {{ form.contactPerson }}
            </el-descriptions-item>
            <el-descriptions-item label="电话：" span="1">
              {{ form.phone }}
            </el-descriptions-item>
            <el-descriptions-item label="备注：" span="1">
              {{ form.remark }}
            </el-descriptions-item>
            <el-descriptions-item label="附件：" span="3">
              <fileUpload v-model="form.fileId" :oldList="form.fileIdOld" :fileType="['doc', 'docx', 'xlsx', 'xls'
                , 'pdf', 'png', 'jpg', 'jpeg']" :disabled="true" />
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <el-table border stripe v-loading="loading" :data="form.detailList" @selection-change="handleSelectionChange">
          <el-table-column type="index" label="序号" width="55" align="center" />
          <el-table-column label="材料编号" align="center" prop="manifestCode" min-width="120" show-overflow-tooltip />
          <el-table-column label="材料名称" align="center" prop="manifestName" min-width="120" show-overflow-tooltip />
          <el-table-column label="规格" align="center" prop="specification" min-width="80" show-overflow-tooltip />
          <el-table-column label="型号" align="center" prop="model" min-width="100" show-overflow-tooltip />
          <el-table-column label="单位" align="center" prop="unit" min-width="80" show-overflow-tooltip />
          <el-table-column label="本月计划数量" align="center" prop="monthPlanPurchaseNumber" min-width="120"
            show-overflow-tooltip />
          <el-table-column label="本次供应数量" align="center" prop="onceSupplyNumber" min-width="120">
            <template slot-scope="scope">
              <el-input v-if="!isReadonly" size="mini" type="number" v-model="scope.row.onceSupplyNumber" />
              <span v-else>{{ scope.row.onceSupplyNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="本月累计供应数量" align="center" prop="monthTotalSupplyNumber" min-width="130"
            show-overflow-tooltip />
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!isReadonly" :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">{{ isReadonly ? "关 闭" : "取 消" }}</el-button>
      </div>
    </jy-dialog>
  </div>
</template>

<script>
import { listMaterialProgress, getMaterialProgressInfoData, allListMaterialProgressDetails, delMaterialProgress, addMaterialProgress, updateMaterialProgress } from "@/api/ma/materialProgress";
import { querySupplierTreeList } from "@/api/base/bsBd";
import { mapGetters } from "vuex";
export default {
  name: "MaterialProgress",
  data () {
    return {
      isHide: false,
      treeList: [],
      treeInfo: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      filterText: undefined,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 材料签收表格数据
      materialProgressList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isReadonly: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bdId: undefined,
        gysId: undefined,
        type: undefined,
        waterCode: undefined,
        acceptanceCode: undefined,
        supplyDate: undefined,
      },
      projectId: undefined,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // progressId: [
        //   { required: true, message: "进度id不能为空", trigger: "blur" }
        // ],
        // bdId: [
        //   { required: true, message: "标段id不能为空", trigger: "blur" }
        // ],
        // gysId: [
        //   { required: true, message: "供应商id不能为空", trigger: "blur" }
        // ],
        // type: [
        //   { required: true, message: "类型id不能为空", trigger: "change" }
        // ],
        // waterCode: [
        //   { required: true, message: "供货流水号不能为空", trigger: "blur" }
        // ],
        acceptanceCode: [
          { required: true, message: "交接验收单据号不能为空", trigger: "blur" }
        ],
        supplyDate: [
          { required: true, message: "供货日期不能为空", trigger: "blur" }
        ],
        phone: [
          { required: false, validator: this.validatePhone, trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(["sysProjectId", "sysProjectList"])
  },
  watch: {
    sysProjectId (newVal, oldVal) {
      // 系统顶部选中项目变化
      this.changeProject(newVal);
    },
    filterText (val) {
      this.$refs.tree.filter(val);
    }
  },
  created () {
    this.changeProject();
  },
  methods: {
    changeProject (projectId = this.sysProjectId) {
      this.projectId = projectId;
      this.getBdTree();
    },
    getBdTree () {
      querySupplierTreeList({ projectId: this.projectId }).then((response) => {
        this.treeList = response.data;
        // 选中左侧树
        this.$nextTick(() => {
          if (this.treeList.length > 0) {
            // this.$refs.tree.setCurrentKey(this.treeList[0].id);
            // this.handleNodeClick(this.treeList[0]);
          } else {
            this.treeInfo = {};
            this.queryParams.bdId = null;
            this.queryParams.zdId = null;
            this.materialProgressList = [];
            this.total = 0;
          }
        });
      });
    },
    // 筛选节点
    filterNode (value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick (data) {
      this.treeInfo = data;
      if (data.type == "supplier") {
        this.queryParams.zdId = data.parentId; // 站点ID
        this.queryParams.gysId = data.id; // 供应商ID
        this.handleQuery();
      } else {
        // this.$message.warning('请选择供应商！');
      }
    },

    /** 查询材料签收列表 */
    getList () {
      this.loading = true;
      listMaterialProgress(this.queryParams).then(response => {
        this.materialProgressList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        progressId: undefined,
        bdId: undefined,
        gysId: this.treeInfo.id,
        type: undefined,
        waterCode: undefined,
        acceptanceCode: undefined,
        supplyDate: undefined,
        address: undefined,
        contactPerson: undefined,
        remark: undefined,
        fileId: undefined,
        detailList: []
      };
      this.resetForm("form");
      this.isReadonly = false;
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.progressId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加材料签收";
      this.form.supplyDate = this.parseTime(new Date().getTime(), '{y}-{m}-{d}');
      this.getMaterialList();
    },
    // 根据供货时间获取材料列表
    getMaterialList () {
      const query = {
        gysId: this.form.gysId,
        supplyDate: this.form.supplyDate
      };
      allListMaterialProgressDetails(query).then(res => {
        this.form.detailList = res.data;
      });
    },
    /** 修改按钮操作 */
    handleUpdate (row, isReadonly) {
      this.loading = true;
      this.reset();
      this.isReadonly = isReadonly;
      const progressId = row.progressId || this.ids;
      getMaterialProgressInfoData(progressId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改材料签收";
        if (this.form.fileId) {
          this.form.fileIdOld = this.form.fileId.split(',');
        }
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.fileId) {
            this.form.fileIds = this.form.fileId.split(',');
          }
          if (this.form.progressId != null) {
            updateMaterialProgress(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addMaterialProgress(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const progressIds = row.progressId || this.ids;
      this.$modal.confirm('是否确认删除交接验收单据号为"' + row.acceptanceCode + '"的数据项？').then(() => {
        this.loading = true;
        return delMaterialProgress(progressIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('ma/materialProgress/export', {
        ...this.queryParams
      }, `materialProgress_${new Date().getTime()}.xlsx`);
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep {
  .descriptions-label {
    width: 120px;
    text-align: right !important;
    padding: 5px 0 !important;
  }

  .descriptions-content {
    // padding: 5px !important;

    .el-form-item {
      margin-bottom: 0px !important;
    }
  }
}
</style>
